package com.lz.gmall.service.Impl;

import com.lz.gmall.config.MinioConfig;
import com.lz.gmall.service.FileUploadService;
import com.lz.gmall.properties.MinioProperties;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioProperties minioProperties;
    /**
     *
     * @param multipartFile 图片文件
     * @return 文件的url
     */
    @Override
    public String fileUpload(MultipartFile multipartFile) {
        String fullFileName = null;
        try {
            // Create a minioClient with the MinIO server playground, its access key and secret key.
            //创建一个minioClient与MinIO server,它的访问密钥和秘密密钥
            MinioClient minioClient = minioConfig.getMinioClient();

            // Make 'asiatrip' bucket if not exist.
            // 判断桶是否存在
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucket()).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                // 如果桶不存在，那么此时就需要创建一个桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucket()).build());
            } else {
                //System.out.println("Bucket 'asiatrip' already exists.");
                System.out.println("gmall的桶是存在的,不用重新创建...");
            }

            //可能在整个业务开发中，其他人会上传同名的文件，会覆盖之前的图片
            //采用uuid的方式作为文件名字
            String uuid = UUID.randomUUID().toString().replace("-", "");
            //获取图片文件的后缀名
            String extension = FilenameUtils.getExtension(multipartFile.getOriginalFilename());
             fullFileName = uuid + "." + extension;

            //FileInputStream fileInputStream = new FileInputStream("D://1.jpg");

            minioClient.putObject(
                    PutObjectArgs.builder().bucket(minioProperties.getBucket()).stream(multipartFile.getInputStream(),multipartFile.getSize(),-1)
                            .object(fullFileName).build()//object 就是设置文件文件名
            );

        }catch (Exception e){
            e.printStackTrace();
        }

        return minioProperties.getEndpoint()+"/"+minioProperties.getBucket()+"/" + fullFileName;
    }
}
